#!/usr/bin/env python
#-IMPORTS----------------------------------------------------------------------
import os
import sys
#-FUNCTIONS--------------------------------------------------------------------
def usage():
    print '\nUsage: test_harness.py PLUGIN IP (ARGS)\n'

def setup_env():
    cwd = os.getcwd()
    sys.path.append(cwd)
    sys.path.append(os.path.split(cwd)[0])

def setup_logging():
    import plogging
    plogging.setup()

def setup_plugin(p_IP='', p_ARGS=None):
    import cmdobj
    cmd = cmdobj.CMD_PARAMS
    cmd[cmdobj.IP] = p_IP
    cmd[cmdobj.ARGS] = p_ARGS
    return cmd

def setup_harness(p_IP='', p_ARGS=None):
    setup_env()
    setup_logging()
    return setup_plugin(p_IP, p_ARGS)

def main(argv=sys.argv):
    if len(argv) < 3:
        usage()
        return 1
    cmd_args = setup_harness(argv[2], argv[3:])
    plugin = argv[1]
    try:
        __import__(plugin , globals(), locals(), [''])
    except:
        print 'EXCEPTION: %s; %s'%(sys.exc_type, plugin)
        return 1
    if hasattr(sys.modules[plugin], sys.modules[plugin].__name__):       
        t_class = getattr(sys.modules[plugin], sys.modules[plugin].__name__)
        import cmdobj
        if issubclass(t_class, cmdobj.CmdObject):
            test = t_class(cmd_args)
            test._start_log()
            test._execute()
        else:
            print '\nERROR: (%s) not imported: Not a subclass of CmdObject (cmdobj.py)\n' % plugin
    else:
        print '\n ERROR: (%s) not imported: File name does not match __name__ attribute.\n' % plugin 
    return 0

if __name__ == '__main__':
    sys.exit(main())

